package com.redrose.audioandvideo.utils;

import com.redrose.audioandvideo.bean.Photo;
import com.redrose.audioandvideo.runnabletask.SaveImageRunnable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

public class FileUtil {
    public static void saveWAV(byte[] date, String filePath, String fileName) {
        File file = new File(filePath + fileName);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(new File(fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void saveImage(byte[] date, List<Photo> list) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
        Calendar calendar = Calendar.getInstance();
        String format = sdf.format(calendar.getTime());
        File dir = new File(PathUtil.getAppPicPath());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String name = PathUtil.getAppPicPath() + format + ".jpg";
        LogUtils.d("FileUtil", "图片保存本地路径： " + name);
        saveData(format, name, list);
        ThreadTask.getInstance().executorOtherThread(new SaveImageRunnable(date, name), ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    private static void saveData(String format, String path, List<Photo> list) {
        Photo photo = new Photo();
        Calendar calendar = Calendar.getInstance();
        photo.setDay(calendar.get(Calendar.DAY_OF_MONTH));
        photo.setMonth(calendar.get(Calendar.MONTH) + 1);
        photo.setClassId(Long.parseLong(format.substring(0, 8)));
        photo.setName(format);
        photo.setTime(format);
        photo.setPath(path);
        photo.setYear(calendar.get(Calendar.YEAR));
        photo.setWeek(calendar.get(Calendar.DAY_OF_WEEK));
        boolean save = photo.save();
        if (save) {
            list.add(photo);
            LogUtils.d("FileUtil", "----图片保存数据库成功");
        }
    }
}
